<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const adv = reactive({
  add: true,
  maxnum: 1,
  forFree: 1,
  setTrueStyle: {},
  imgs: [],
  option: {
    viewMode: 0,
    dragMode: 'move',
    aspectRatio: 1,
    autoCropArea: 1,
    center: false,
    cropBoxMovable: false,
    cropBoxResizable: false,
    toggleDragModeOnDblclick: false
  },
  cropImg: proxy.$Global.cropImg
})

/* ---- */
const uploadoss = ref()
const layer = ref()
const layerLoading = ref()

/* ---- */
const getFormInfo = () => {
  adv.setTrueStyle = { height: `${document.querySelector('.squareBox dl dd label').clientWidth / adv.forFree}px` }
  // ----
  proxy.$Myfun.getJsonData(logUser.avatar, (resJson) => {
    resJson.forEach((item) => {
      adv.imgs.push({
        imgName: item.name,
        imgUrl: item.image,
        imgW: item.width,
        imgH: item.height
      })
    })
    if (Number(adv.imgs.length) >= Number(adv.maxnum) && Number(adv.maxnum) > 0) adv.add = !adv.add
  })
}
// --上传图片操作--
const uploadAct = (type, selectObj, event, index) => {
  const uploadOss = uploadoss.value
  switch (Number(type)) {
    case 1: {
      uploadOss.uploadImg(event, selectObj,'imgs', index)
      break
    }
    case 2: {
      uploadOss.delInfo(selectObj, event)
      break
    }
  }
}
// ----
const setDefault = async (opts) => {
  let forItems = []
  await proxy.$http[opts.forSch.type](opts.forSch.url, opts.forSch.data).then((res) => {
    forItems = res.items
  }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  if (Number(forItems.length) === 0) return false
  // ----
  for (let i = 0; i < Number(forItems.length); i++) {
    await setSecond(forItems[i], opts.forUte)
  }
}
const setSecond = async (item, opts) => {
  if (opts.key && Number(opts.key.length) > 0) {
    const imgItems = []
    adv.imgs.forEach((item) => {
      imgItems.push({
        name: item.imgName,
        image: item.imgUrl,
        width: item.imgW,
        height: item.imgH
      })
    })
    // ----
    let forRemark = {}
    proxy.$Myfun.getJsonData(item[opts.key], (resJson) => { if (Number(resJson.length) > 0) forRemark = resJson[0] })
    // ----
    forRemark.avatar = imgItems
    // ----
    opts.data[opts.key] = JSON.stringify(forRemark)
  }
  // ----
  await proxy.$http[opts.type](opts.url + item.id, opts.data).then((res) => {}).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
}
const subform = async () => {
  let forImg = null
  if (Number(adv.imgs.length) > 0) {
    const imgItems = []
    adv.imgs.forEach((item) => {
      imgItems.push({
        name: item.imgName,
        image: item.imgUrl,
        width: item.imgW,
        height: item.imgH
      })
    })
    forImg = JSON.stringify(imgItems)
  }
  // ----
  const forType = 'patch'
  const forUrl = 'dealer/update?id=' + logUser.id
  const forData = {
    avatar: forImg || undefined,
    // ----
    config_id: userInfo.config_id,
    openid: userInfo.openid
  }
  // ----
  proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
  let resData = ''
  await proxy.$http[forType](forUrl, forData).then((res) => { resData = res }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  if (resData) {
    // --更新分销商友简短信息--
    const options = {
      forSch: {
        type: 'get',
        url: 'cloud-has-storage/index',
        data: {
          params: {
            'CloudHasStorage[to_dealer_id]': logUser.id,
            // ----
            page: 1,
            PageSize: 1000000000000
          }
        }
      },
      forUte: {
        type: 'patch',
        url: 'cloud-has-storage/update?id=',
        data: {
          config_id: userInfo.config_id,
          openid: userInfo.openid
        },
        key: 'remark'
      }
    }
    await setDefault(options)
    // ----
    proxy.$Myfun.disLoading(layerLoading.value, 'close')
    proxy.$router.back()
  } else {
    proxy.$Myfun.disLoading(layerLoading.value, 'close')
  }
}
const goback = () => { proxy.$router.back() }

/* ---- */
onMounted(() => {
  getFormInfo()
})
onBeforeRouteLeave(() => { proxy.$Myfun.setScrollTop(proxy.$refs.formSection) })
</script>

<template>
  <div class="mescroll-touch" ref="formSection">
    <div class="formSet">
      <ul>
        <li>
          <div class="form-imgs xw-radius-3 squareBox">
            <dl class="FIS-img">
              <dd v-for="(item, index) in adv.imgs"><label class="xw-block xw-act"><img :src="item.imgUrl"/><input type="file" style="display: none;" accept="image/*" @change="uploadAct(1, adv, $event, index)"/></label><span class="FIS-del fal fa-times xw-act" @click="uploadAct(2, adv, index)"></span></dd>
              <dd v-if="adv.add"><label class="xw-act xw-flex xw-flex-center" :style="adv.setTrueStyle"><em class="fal fa-plus"></em><input type="file" style="display: none;" accept="image/*" @change="uploadAct(1, adv, $event)"/></label></dd>
            </dl>
          </div>
        </li>
      </ul>
      <div class="form-sub xw-radius-3 xw-bgCL-11 xw-act" @click="subform">确定提交</div>
      <div class="form-sub xw-radius-3 xw-WhiteRed xw-act" @click="goback">取消返回</div>
    </div>
    <uploadoss-view ref="uploadoss"/>
    <layer-view ref="layer"/>
    <layer-view ref="layerLoading"/>
  </div>
</template>